package liveDemo.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import liveDemo.model.LiveRedis;
import liveDemo.model.UserRedis;
import liveDemo.service.LiveService;
import liveDemo.service.UserService;

@RestController
public class LoginController {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	UserService userService;
	
	@Autowired
	private LiveService liveService;
	
	//跳到登录页面
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView toLogin(ModelMap model) {
		model.addAttribute("user", new UserRedis());
		return new ModelAndView("login");
	}
	
	//进行登录判断
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(Model model, @ModelAttribute(value = "user") UserRedis user, HttpSession session) {
		String url = "liveList"; //返回的url
		if(userService.isUser(user)) { //service层进行用户名和密码判断正确
			session.setAttribute("user", user);
			List<LiveRedis> list = liveService.getAll();
			model.addAttribute("liveList", list);
		}else {   //密码或用户名错误
			model.addAttribute("user", user);
			model.addAttribute("messages", "账号或密码错误!");
			logger.info("用户名 = " + user.getName()); //打印日记信息
			 url= "login";
		}
		return new ModelAndView(url);
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ModelAndView logout(Model model, HttpSession session) {
		session.invalidate(); //设置session失效
		model.addAttribute("user", new UserRedis());
		return new ModelAndView("login");
	}

}
